package com.lian.chatroom.server.handler;

import com.lian.chatroom.message.GroupJoinRequestMessage;
import com.lian.chatroom.message.GroupJoinResponseMessage;
import com.lian.chatroom.server.session.Group;
import com.lian.chatroom.server.session.GroupSession;
import com.lian.chatroom.server.session.GroupSessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * 加入群组处理器
 */
@ChannelHandler.Sharable
public class GroupJoinRequestMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        Group group = groupSession.joinMember(groupName, username);
        if (group != null){
            ctx.writeAndFlush(new GroupJoinResponseMessage(true,groupName + "群加入成功"));
        }else {
            ctx.writeAndFlush(new GroupJoinResponseMessage(false,groupName + "群不存在"));
        }
    }
}
